package engine.planner;

import java.util.ArrayList;
import java.util.List;

import engine.planner.QueryData;
import engine.query.Plan;
import engine.query.ProductPlan;
import engine.query.ProjectPlan;
import engine.query.SelectPlan;
import engine.query.TablePlan;

import server.starDB;
import storage.tx.Transaction;
public class BasicQueryPlanner implements QueryPlanner{

	@Override
	public Plan createPlan(QueryData data, Transaction tx) {
		//Step 1: Create a plan for each mentioned table or view
			List<Plan> plans = new ArrayList<Plan>();
			for (String tblname : data.tables()) {
				String viewdef = starDB.mdMgr().getViewDef(tblname, tx);
				if (viewdef != null)
					plans.add(starDB.planner().createQueryPlan(viewdef, tx));
				else
					plans.add(new TablePlan(tblname, tx));
			}
			for(QueryData qd : data.subtables){
				plans.add(createPlan(qd,tx));
			}
			
		//Step 2: Create the product of all table plans
			Plan p = plans.remove(0);
			for (Plan nextplan : plans)
				p = new ProductPlan(p, nextplan);

		//Step 3: Add a selection plan for the predicate
			p = new SelectPlan(p, data.pred());

		//Step 4: Project on the field names
			p = new ProjectPlan(p, data.fields());
			return p;
		}
}
